import { Component, Vue, Prop, PropSync, Watch } from 'vue-property-decorator'
import styles from '@/views/NewApply/NewApply.less'
import { State, Action, Mutation } from 'vuex-class'
import { RootState } from '@/store'
import SealDetail from '@/views/AppliedForMe/SealDetail'
import OperationCol from '@/components/OperationCol'
import SealStatus, { issueList } from '@/components/SealStatus'
import OrganizeTree from '@/components/OrganizeTree'
import {
  orgLicenseTypes,
  orgTypes,
  userLicenseTypes,
  adminTypes,
  useTypes,
  formatStatus,
  sealTypes,
} from '@/lib/sealFormat'
import { desensitization } from '@/lib/utils'
import { ElTable } from 'element-ui/types/table'
import TableEmpty from '@/components/tableEmpty'

@Component({})
export default class AuthSeal extends Vue {
  @PropSync('selection', { default: () => [] }) selectList!: any[] // 已选择的
  @Prop({ default: false }) isUpdate!: boolean // 变更数据权限
  @Prop({ default: false }) isAuth!: boolean // 是否授权/取消授权
  @Prop({ default: '' }) appId!: string // 变更数据权限的应用id
  @Prop({ default: '' }) emptyText!: string
  @State((state: RootState) => state.myManagingSeal.sealList)
  sealList!: any[]
  @State((state: RootState) => state.myManagingSeal.total)
  total!: number
  @State((state: RootState) => state.myManagingSeal.detailVisible)
  detailVisible!: boolean
  @State((state: RootState) => state.myManagingSeal.organizeUuid)
  organizeUuid!: string
  @State((state: RootState) => state.myManagingSeal.loading)
  loading!: boolean
  @State((state: RootState) => state.myManagingSeal.sealData)
  sealData?: any

  sealType: number[] = []
  status: number[] = []
  sealName: string = ''
  pageIndex: number = 1
  pageSize: number = 10
  sealCode: string = ''
  range: number = 2 // 1:仅本级部门 2:本级及下级
  sealUseType: number[] = [2] // 用章方式 1:Ukey签章 2:云签章
  authorized: number = 0 // 是否被授权印章管理员 1:授权 2:未授权
  resetVisible: boolean = false // 控制树
  authorizeList: any[] = [] // 每页列表中已授权的印章

  @Mutation('myManagingSeal/setStateData') setStateData!: any
  @Action('myManagingSeal/getList') getList!: any
  @Action('myManagingSeal/sealDetail') sealDetail!: any

  protected render() {
    return (
      <div class={{ [styles.container]: true, p10: true }}>
        {!this.resetVisible && (
          <OrganizeTree
            class={{ [styles.treeBlock]: true }}
            on-handle-node-click={this.handleNodeClick}
          />
        )}
        <div class={{ [styles.queryBlock]: true }}>
          <div class={{ [styles.query]: true, custom: true }}>
            <span class={styles.part}>
              <span>印章名称</span>
              <el-input v-model={this.sealName} />
            </span>
            <span class={styles.part}>
              <span>印章类别</span>
              <el-select
                v-model={this.sealType}
                multiple
                collapse-tags
                placeholder="默认全部"
              >
                {sealTypes.map((sealType: any, index: number) => (
                  <el-option
                    key={sealType.id}
                    label={sealType.value}
                    value={sealType.id}
                  />
                ))}
              </el-select>
            </span>
            <span class={styles.part}>
              <span>印章编码</span>
              <el-input v-model={this.sealCode} />
            </span>
            <span class={styles.part}>
              <span>印章状态</span>
              <el-select
                v-model={this.status}
                multiple
                collapse-tags
                placeholder="默认全部"
              >
                {issueList
                  .filter(sealType => sealType.key !== 3)
                  .map((sealType: any, index: number) => (
                    <el-option
                      key={sealType.key}
                      label={sealType.text}
                      value={sealType.key}
                    />
                  ))}
              </el-select>
            </span>
            {/* <span class={styles.part}>
              <span>检索范围</span>
              <el-select v-model={this.range} disabled={!this.organizeUuid}>
                <el-option label="本级及下级" value={2} />
                <el-option label="仅本级部门" value={1} />
              </el-select>
            </span> */}
            {/* <span class={styles.part}>
              <span>用章方式</span>
              <el-select multiple v-model={this.sealUseType}>
                <el-option label="Ukey签章" value={1} />
                <el-option label="云签章" value={2} />
              </el-select>
            </span> */}
            <span class={styles.part}>
              <el-button
                plain
                class="min color-blue"
                loading={this.loading}
                onClick={this.query}
              >
                搜索
              </el-button>
              <el-button plain class="min color-gray" onClick={this.reset}>
                重置
              </el-button>
            </span>
          </div>
          <el-table
            data={this.sealList}
            style="width: 100%"
            v-loading={this.loading}
            onSelect={this.selectHandle}
            onSelect-all={this.selectAllHandle}
            ref="table"
            empty-text={this.emptyText}
          >
            <TableEmpty
              slot="empty"
              msg={this.emptyText}
              url={require('@/assets/seal-empty.svg')}
              v-show={!this.loading}
            >
              <el-button type="primary" onClick={this.toProjectList}>
                返回授权应用列表
              </el-button>
            </TableEmpty>
            <el-table-column type="selection" width="55" />
            <el-table-column
              prop="sealCode"
              label="印章编码"
              min-width="140"
              show-overflow-tooltip
            />
            <el-table-column
              prop="sealName"
              label="印章名称"
              min-width="140"
              show-overflow-tooltip
            />
            {/* <el-table-column
              prop="name"
              label="印章图片"
              min-width="100"
              {...{
                scopedSlots: {
                  default: (scope: any) => {
                    return (
                      <img
                        src={scope.row.sealPicUrl}
                        height="25"
                        alt="印章图片"
                      />
                    )
                  },
                },
              }}
            /> */}
            <el-table-column
              prop="sealType"
              label="印章类别"
              min-width="80"
              show-overflow-tooltip
              {...{
                scopedSlots: {
                  default: (scope: any) => {
                    return formatStatus(sealTypes, scope.row.sealType)
                  },
                },
              }}
            />
            <el-table-column
              prop="organizeName"
              label="用章机构名称"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column
              prop="endTime"
              label="到期时间"
              show-overflow-tooltip
            />
            <el-table-column
              prop="sealStatus"
              label="状态"
              {...{
                scopedSlots: {
                  default: (scope: any) => {
                    return <SealStatus issue status={scope.row.sealStatus} />
                  },
                },
              }}
            />
            <el-table-column
              prop="id"
              label="操作"
              width="200"
              {...{
                scopedSlots: {
                  default: (scope: any) => {
                    return (
                      <span>
                        <OperationCol
                          operations={this.filterOptions(
                            scope.row.sealStatus,
                            scope.row.sealApplyType
                          )}
                          showNum={4}
                          row={scope.row}
                          index={scope.$index}
                        />
                      </span>
                    )
                  },
                },
              }}
            />
          </el-table>
          {this.sealList && this.sealList.length > 0 && (
            <el-pagination
              class={{ [styles.pagination]: true }}
              onSize-change={this.handleSizeChange}
              onCurrent-change={this.handleCurrentChange}
              current-page={this.pageIndex}
              page-sizes={[10, 20, 30]}
              page-size={this.pageSize}
              layout="total, sizes, prev, pager, next, jumper"
              total={this.total}
              pager-count={5}
            />
          )}
        </div>

        <SealDetail
          detailItems={{
            eSealBasicInfo: true,
            sealOrgBasicInfo: true,
            sealUserBasicInfo: false,
            digitalCertBasicInfo: true,
            sealAdminBasicInfo: true,
          }}
          onVisibleChange={(val: boolean) => {
            this.setStateData({ detailVisible: val })
          }}
          data={this.sealData}
          visible={this.detailVisible}
        >
          <template slot="sealAdminBasicInfo">
            <el-table
              data={this.sealData && this.sealData.managerAccounts}
              class={{ [styles.detailTable]: true }}
            >
              <el-table-column prop="name" label="印章管理员" />
              <el-table-column
                prop="mobile"
                label="手机号"
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return <span>{desensitization(scope.row.mobile)}</span>
                    },
                  },
                }}
              />
            </el-table>
          </template>
        </SealDetail>
      </div>
    )
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 1,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.detail(rows)
        },
      },
      {
        id: 2,
        text: this.isAuth ? '授权' : '取消授权',
        onClick: (index: number, rows: any) => {
          this.authSeal(rows)
        },
      },
    ]

    return btns
  }

  @Watch('selectList.length')
  selectListChange(val: number) {
    this.showSelects()
  }

  async mounted() {
    this.setStateData({ organizeUuid: '' })
    this.query()
  }

  handleNodeClick(val: any) {
    this.setStateData({ organizeUuid: val })
    this.query()
  }

  filterOptions(status: number, sealApplyType: number) {
    if (this.isUpdate) {
      return this.getOperations
    }

    return [this.getOperations[0]]
  }

  authSeal(row: any) {
    this.$emit('auth', row)
  }

  detail(row: any) {
    this.sealDetail(row.sealSn).then((data: any) => {
      this.setStateData({
        detailVisible: true,
        sealData: Object.assign({}, data, {
          organizeType: formatStatus(orgTypes, data.organizeType),
          organizeCardType: formatStatus(
            orgLicenseTypes,
            data.organizeCardType
          ),
          organizeLevel: formatStatus(adminTypes, data.organizeLevel),
          inspectCardType: formatStatus(userLicenseTypes, data.inspectCardType),
          sealType: formatStatus(sealTypes, data.sealType),
          sealUseType: formatStatus(useTypes, data.sealUseType),
          inspectMobileDes: desensitization(data.inspectMobile),
          inspectCardIdDes: desensitization(data.inspectCardId),
        }),
      })
      this.setStateData({ detailVisible: true })
    })
  }

  toProjectList() {
    this.$router.push({ name: 'authorizeApp' })
  }

  query() {
    this.pageIndex = 1
    this.queryList()
  }
  async queryList() {
    // 新增授权印章
    await this.getList({
      sealName: this.sealName,
      sealType: this.sealType,
      sealStatus:
        this.status.length === 0 && !this.isUpdate
          ? issueList.filter(type => type.key !== 3).map(type => type.key)
          : this.status, // 当为授权新应用时需要手动传，过滤掉已吊销的印章
      range: this.range,
      sealCode: this.sealCode,
      organizeUuid: this.organizeUuid,
      sealUseType: this.sealUseType,
      pageIndex: this.pageIndex,
      pageNumber: this.pageSize,
      authorize: !this.isAuth, // 授权印章需要查询未授权印章or取消授权印章需要查询已授权印章
      projectId:
        this.appId || (this.isUpdate ? this.$route.query.id : undefined),
    })
    const table = this.$refs.table as ElTable
    table.doLayout()
    this.showSelects()
  }

  handleSizeChange(val: number) {
    this.pageSize = val
    this.query()
  }

  handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  reset() {
    this.sealType = []
    this.status = []
    this.sealName = ''
    this.sealCode = ''
    this.range = 2
    this.setStateData({ organizeUuid: '' })
    this.resetVisible = true
    this.$nextTick(() => {
      // 重置所选
      this.resetVisible = false
    })
    this.query()
  }

  selectHandle(selection: any[], row: any) {
    if (
      this.selectList.findIndex(a => {
        return a.sealCode === row.sealCode
      }) < 0
    ) {
      this.$emit('selectChange', this.selectList.concat([row]))
    } else {
      const list = this.selectList
      list.splice(
        this.selectList.findIndex(a => {
          return a.sealCode === row.sealCode
        }),
        1
      )
      this.$emit('selectChange', list)
    }
  }

  selectAllHandle(selection: any) {
    if (selection.length === this.authorizeList.length) {
      const list = this.selectList.filter((select: any) => {
        return (
          this.sealList.findIndex(a => {
            return a.sealCode === select.sealCode
          }) < 0
        )
      })
      this.$emit('selectChange', list)
    } else {
      const arr = this.selectList.concat(selection).filter(seal => {
        return (
          this.authorizeList.findIndex(a => {
            return a.sealCode === seal.sealCode
          }) < 0
        )
      })
      this.$emit('selectChange', this.unique(arr))
    }
  }

  showSelects() {
    // 部门列表懒加载、tag和列表checkbox联动时同步列表的checkbox数据
    this.$nextTick(() => {
      ;(this.$refs.table as ElTable).clearSelection()
      // if (this.isUpdate) {
      //   // 自动勾选已授权印章
      //   this.authorizeList = this.sealList
      //     .filter(seal => seal.authorize)
      //     .map(seal => {
      //       ;(this.$refs.table as ElTable).toggleRowSelection(seal)

      //       return seal
      //     })
      // }
      this.sealList.map(app => {
        if (
          this.selectList.filter(
            (select: any) => select.sealCode === app.sealCode
          ).length > 0
        ) {
          ;(this.$refs.table as ElTable).toggleRowSelection(app)
        }

        return app
      })
    })
  }
  unique(arr: any[]) {
    // 去重
    return arr.filter(function(item, index, arr) {
      // 当前元素，在原始数组中的第一个索引==当前索引值，否则返回当前元素
      return (
        arr.findIndex(a => {
          return a.sealCode === item.sealCode
        }) === index
      )
    })
  }
}
